package com.jackin.smsobserverdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.tuenti.smsradar.Sms;
import com.tuenti.smsradar.SmsListener;
import com.tuenti.smsradar.SmsRadar;

/**
 * 测试主页面
 */
public class MainActivity extends AppCompatActivity {

    private final String TAG = MainActivity.class.getSimpleName();
    private TextView smsContent;
    private Button startService;
    private Button stopService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mapGui();
        hookListeners();
        initializeSmsRadarService();
    }

    private void mapGui() {
        smsContent = (TextView) findViewById(R.id.textView);
        startService = (Button) findViewById(R.id.button);
        stopService = (Button) findViewById(R.id.button2);
    }

    private void hookListeners() {
        startService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initializeSmsRadarService();
            }
        });
        stopService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stopSmsRadarService();
            }
        });
    }

    private void initializeSmsRadarService() {
        Log.d(TAG, "start listening service...");
        SmsRadar.initializeSmsRadarService(this, new SmsListener() {
            @Override
            public void onSmsSent(Sms sms) {
                showSmsToast(sms);
            }

            @Override
            public void onSmsReceived(Sms sms) {
                showSmsToast(sms);
            }
        });
        Log.d(TAG, "started listening service !");
    }

    private void stopSmsRadarService() {
        Log.d(TAG, "stop listening service...");
        SmsRadar.stopSmsRadarService(this);
        Log.d(TAG, "stoped listening service...");
    }

    private void showSmsToast(Sms sms) {
        Toast.makeText(this, sms.toString(), Toast.LENGTH_LONG).show();
        smsContent.setText(String.format("最新消息：%s", sms.toString()));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopSmsRadarService();
    }
}
